package com.reader.api.utils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
 * @author jiahaikun
 * @date 2018/11/07
 * 公共调用方法
 */
public class CommonFunction {

    /**
     * 数据源 List<HashMap<String, Object>>  按指定字段分组;
     * @param groupKey 分组字段
     * @param listKey  下级分组内容list
     * @param source   分组数据
     * @return
     */
    public  static  List<HashMap<String, Object>> getGroupList(String groupKey,
                                                              String listKey ,
                                                              List<HashMap<String, Object>> source){
        List<HashMap<String, Object>> grouplist = source.stream()
                .collect(Collectors.groupingBy(q -> q.get(groupKey)))
                .entrySet()
                .stream()
                .map(e -> {
                    HashMap<String, Object> inner = new HashMap<>();
                    List<Map<String, Object>> newList = e.getValue().stream().map(v -> {
                        v.remove(groupKey);
                        return v;
                    }).collect(Collectors.toList());
                    inner.put(listKey, newList);
                    inner.put(groupKey,e.getKey());
                    return inner;
                }).collect(Collectors.toList());

        return grouplist;
    }


    public  static  List<HashMap<String, Object>> getGroupList(String groupKey,
                                                               String listKey ,
                                                               List<HashMap<String, Object>> source,
                                                               String ... GroupParam){
        List<HashMap<String, Object>> grouplist = source.stream()
                .collect(Collectors.groupingBy(q -> q.get(groupKey)))
                .entrySet()
                .stream()
                .map(e -> {
                    HashMap<String, Object> inner = new HashMap<>();
                    List<Map<String, Object>> newList = e.getValue().stream().map(v -> {
                        v.remove(groupKey);
                        return v;
                    }).collect(Collectors.toList());
                    inner.put(listKey, newList);
                    inner.put(groupKey,e.getKey());
                    return inner;
                }).collect(Collectors.toList());

        return grouplist;
    }
}
